package com.zhugang.week01;

/**
 * @program algorithms
 * @description: 最后一个单词长度
 * @author: chanzhugang
 * @create: 2022/03/23 07:09
 */
public class LengthOfLastWord {

    public static void main(String[] args) {
        LengthOfLastWord lastWord = new LengthOfLastWord();
        String s = "hello world   ";
        int length = lastWord.lengthOfLastWord(s);
        System.out.println(length);
    }

    public int lengthOfLastWord(String s) {
        // 从后往前扫描，去掉尾部空格
        int i = s.length() - 1;
        while (i > 0 && s.charAt(i) == ' ') {
            i--;
        }
        int k = 0;
        // 找到空格分隔点,统计最后一个单词长度
        while (i > 0 && s.charAt(i) != ' ') {
            i--;
            k++;
        }
        return k;
    }
}